﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Primitive.Threading.Sync
{
    struct SimpleSpinLock
    {
        private int m_resource_in_use;//0=false(默认),1=true

        public void Enter()
        {
            //将资源设置为"正在使用"(1),如果这个现场是把它从"自由使用"(0)
            //变成"正在使用"(1)就返回,以便执行Enter调用之后的代码.
            while (Interlocked.Exchange(ref m_resource_in_use, 1) != 0)
            {
                /*black magic放在这里...*/
            }
        }

        public void Leave()
        {
            //将资源标记为"自由使用"{0}
            Thread.VolatileWrite(ref m_resource_in_use, 0);
        }
    }

    class SomeResource
    {
        private SimpleSpinLock m_s1 = new SimpleSpinLock();
        public void AccessResource()
        {
            m_s1.Enter();
            //一次只有一个线程才能进入这个访问资源...
            m_s1.Leave();
        }
    }
}
